package cn.xuewenbao.edu.service.impl;

import cn.xuewenbao.edu.controller.ESController;
import cn.xuewenbao.edu.entity.*;
import cn.xuewenbao.edu.entity.vo.*;
import cn.xuewenbao.edu.mapper.CourseMapper;
import cn.xuewenbao.edu.service.*;
import cn.xuewenbao.eduorder.entity.Eduorder;
import cn.xuewenbao.eduorder.service.EduorderService;
import cn.xuewenbao.ucenter.entity.Member;
import cn.xuewenbao.ucenter.service.FollowService;
import cn.xuewenbao.ucenter.service.MemberService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程表 服务实现类
 * </p>
 *
 * @author mafayu
 * @since 2021-03-30
 */
@Service
@Slf4j
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    private static final String COURSE_TYPE = "2";

    @Autowired
    private CourseChapterService chapterService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private FollowService followService;

    @Autowired
    private GoodLinkService linkService;

    @Autowired
    private ContentSubjectService contentSubjectService;

    @Autowired
    private ColumnDataService columnDataService;

    @Autowired
    private ESController esController;

    @Autowired
    private EduorderService orderService;

    @Autowired
    private ViewContentService viewContentService;

    @Autowired
    private FavoriteService favoriteService;

    @Autowired
    private LearnRecordService learnRecordService;

    //根据课程id查询课程基本信息
    @Override
    public Result<CourseInfoVo> getCourseInfo(String courseId, String userId) {
        Result<CourseInfoVo> result = new Result<>();
        Course course = baseMapper.selectById(courseId);
        if (course == null) {
            result.setSuccess(false);
            result.setMessage("课程为空");
            return result;
        }
        //将阅读记录添加到阅读表中
        ViewContent viewContent = new ViewContent();
        viewContent.setContentId(courseId);
        viewContent.setColumnType(COURSE_TYPE);
        viewContent.setAuthorId(course.getTeacherId());
        viewContent.setUserId(userId);
        viewContentService.save(viewContent);

        //将课程信息先复制到CourseInfoVo
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        BeanUtils.copyProperties(course, courseInfoVo);
        //得到课程章节信息
        QueryWrapper<CourseChapter> chapterQueryWrapper = new QueryWrapper<>();
        chapterQueryWrapper.eq("course_id", courseId);
        List<CourseChapter> courseChapterList = chapterService.list(chapterQueryWrapper);
        List<CourseChapterVo> courseChapterVoList = new ArrayList<>();
        for (int i = 0; i < courseChapterList.size(); i++) {
            CourseChapter courseChapter = courseChapterList.get(i);
            //将信息复制到VO类
            CourseChapterVo courseChapterVo = new CourseChapterVo();
            BeanUtils.copyProperties(courseChapter, courseChapterVo);
            Double currentTime = learnRecordService.getCurrentTime(userId, courseId, COURSE_TYPE, courseChapter.getId());
            if (currentTime != null) {
                courseChapterVo.setCurrentTime(currentTime);
            } else {
                courseChapterVo.setCurrentTime(0.0);
            }
            courseChapterVoList.add(courseChapterVo);
        }
        //得到讲师信息
        Member member = memberService.getById(course.getTeacherId());
        String username = member.getUsername();
        String avatar = member.getAvatar();
        String description = member.getDescription();
        courseInfoVo.setTeacherUsername(username);
        courseInfoVo.setTeacherDescription(description);
        courseInfoVo.setAvatar(avatar);
        //得到课程描述
        String course_description = course.getDescription();
        courseInfoVo.setCourseDescription(course_description);
        //得到最终课程信息
        courseInfoVo.setCourseChapterVos(courseChapterVoList);
        //得到是否关注作者
        Result<?> followResult = followService.hasFollowOne(userId, course.getTeacherId());
        courseInfoVo.setIsFollow(followResult.isSuccess());

        //得到是否收藏以及收藏数
        Result<?> favoriteResult = favoriteService.hasFavoriteOne(userId, courseId);
        courseInfoVo.setHasFavorite(favoriteResult.isSuccess());

        Long favNum = favoriteService.totalNum(courseId);
        courseInfoVo.setFavoriteCount(favNum);

        //得到是否已购买
        QueryWrapper<Eduorder> orderWrapper = new QueryWrapper<>();
        orderWrapper.eq("member_id", userId).eq("content_id", courseId).eq("column_type", COURSE_TYPE).eq("status", 1).last("LIMIT 1");
        Eduorder order = orderService.getOne(orderWrapper);
        if (order != null) {  //订单已存在并已支付
            courseInfoVo.setHasPurchased(true);
        } else {
            courseInfoVo.setHasPurchased(false);
        }
        result.setResult(courseInfoVo);
        result.setSuccess(true);
        return result;
    }

    //获取推荐课程（根据发布时间倒序排列）
    @Override
    public Result<List<CourseIndexVo>> getRecommendCourse() {
        Result<List<CourseIndexVo>> result = new Result<>();
        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        wrapper.eq("status","Approval");
        wrapper.orderByAsc("gmt_create");
        List<Course> courseList = baseMapper.selectList(wrapper);
        List<CourseIndexVo> courseIndexVoList = new ArrayList<>();
        for (int i = 0; i < courseList.size(); i++) {
            CourseIndexVo courseIndexVo = new CourseIndexVo();
            Course course = courseList.get(i);
            BeanUtils.copyProperties(course, courseIndexVo);
            courseIndexVoList.add(courseIndexVo);
        }
        result.setSuccess(true);
        result.setResult(courseIndexVoList);
        return result;
    }

    //获取热门课程（根据购买数）
    @Override
    public Result<List<CourseIndexVo>> getHotCourse() {
        Result<List<CourseIndexVo>> result = new Result<>();
        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        wrapper.eq("status","Approval");
        wrapper.orderByDesc("buy_count");
        List<Course> courseList = baseMapper.selectList(wrapper);
        List<CourseIndexVo> courseIndexVoList = new ArrayList<>();
        for (int i = 0; i < courseList.size(); i++) {
            CourseIndexVo courseIndexVo = new CourseIndexVo();
            Course course = courseList.get(i);
            BeanUtils.copyProperties(course, courseIndexVo);
            courseIndexVoList.add(courseIndexVo);
        }
        result.setSuccess(true);
        result.setResult(courseIndexVoList);
        return result;
    }

    //添加课程
    @Override
    public Result<?> addCourse(CoursePulishVo coursePulishVo) {
        Result<String> result = new Result<>();
        //1 向课程表添加课程基本信息
        Course course = new Course();
        BeanUtils.copyProperties(coursePulishVo, course);
        int insert = baseMapper.insert(course);
        if (insert == 0) {
            result.setSuccess(false);
            result.setMessage("添加课程失败");
            return result;
        }
        String cid = course.getId();

        //添加好物推荐
        GoodVo goodVo = coursePulishVo.getGoodVo();
        if (goodVo == null) {
            result.setMessage("好物链接为空");
        } else {
            GoodLink goodLink = new GoodLink();
            BeanUtils.copyProperties(goodVo, goodLink);
            goodLink.setGoodId(course.getId());
            goodLink.setUserId(coursePulishVo.getTeacherId());
            goodLink.setType("course");
            linkService.save(goodLink);
            result.setMessage("添加好物链接成功");
        }

        //添加课程章节
        List<CourseChapterInfo> courseChapterInfos = coursePulishVo.getCourseChapterVos();
        for (int i = 0; i < courseChapterInfos.size(); i++) {
            CourseChapter courseChapter = new CourseChapter();
            CourseChapterInfo courseChapterInfo = courseChapterInfos.get(i);
            BeanUtils.copyProperties(courseChapterInfo, courseChapter);
            courseChapter.setCourseId(cid);
            final val save = chapterService.save(courseChapter);
            if (save == false) {
                result.setSuccess(false);
                result.setMessage("添加课程章节失败");
                return result;
            }
        }
        //添加三级分类
        val subjectList = coursePulishVo.getSubjectList();
        for (String s : subjectList) {
            ContentSubject contentSubject = new ContentSubject();
            contentSubject.setContentId(cid);
            contentSubject.setSubjectId(s);
            contentSubject.setColumnType(COURSE_TYPE);
            contentSubjectService.save(contentSubject);
        }

        Boolean dataInsertSuccess = columnDataService.addColumnData(cid, COURSE_TYPE, 0L, 0L, 0L, 0L);
        if (!dataInsertSuccess) {
            return Result.error("插入课程数据失败");
        }

        result.setMessage("添加课程成功");
        result.setResult(cid);
        result.setSuccess(true);
        return result;
    }

    //根据课程id删除课程
    @Override
    public Result<?> removeCourse(String courseId) {
        Result<?> result = new Result<>();
        //根据课程id删除章节
        chapterService.deleteChapterByCourseId(courseId);

        //根据课程id删除课程本身
        int count = baseMapper.deleteById(courseId);
        if (count == 0) {
            result.setSuccess(false);
            result.setMessage("删除课程失败");
            return result;
        }
        result.setSuccess(true);
        result.setMessage("删除课程成功");
        return result;
    }

    //根据课程id和作者id删除课程
    @Override
    public Result<?> deleteOwnCourse(String courseId, String userId) {
        Result<?> result = new Result<>();
        Course course = baseMapper.selectById(courseId);
        if (course == null) {
            result.setMessage("课程为空");
            result.setSuccess(false);
            return result;
        }
        if (!course.getTeacherId().equals(userId)) {
            result.setMessage("没有删除权限");
            result.setSuccess(false);
            return result;
        }
        //根据课程id删除章节
        chapterService.deleteChapterByCourseId(courseId);

        //根据课程id删除课程本身
        int count = baseMapper.deleteById(courseId);
        if (count == 0) {
            result.setSuccess(false);
            result.setMessage("删除课程失败");
            return result;
        }
        result.setSuccess(true);
        result.setMessage("删除课程成功");
        return result;
    }

    @Override
    public Result<List<CourseIndexVo>> getOwnCourse(String teacherId) {
        Result<List<CourseIndexVo>> result = new Result<>();
        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        wrapper.eq("status","Approval");
        wrapper.eq("teacher_id", teacherId);
        List<Course> courseList = baseMapper.selectList(wrapper);
        List<CourseIndexVo> courseIndexVoList = new ArrayList<>();
        for (int i = 0; i < courseList.size(); i++) {
            CourseIndexVo courseIndexVo = new CourseIndexVo();
            Course course = courseList.get(i);
            BeanUtils.copyProperties(course, courseIndexVo);
            courseIndexVoList.add(courseIndexVo);
        }
        result.setSuccess(true);
        result.setResult(courseIndexVoList);
        return result;
    }

    @Override
    public String getOrderDescription(String contentId) {
        Course course = baseMapper.selectById(contentId);
        if (course == null) {
            return null;
        }
        return course.getDescription();
    }

    //根据课程id获取课程购买链接
    @Override
    public Result<CourseBuyLink> getCourseBuyLink(String courseId) {
        Result<CourseBuyLink> result = new Result<>();
        Course course = baseMapper.selectById(courseId);
        if (course==null){
            result.setSuccess(false);
            result.setMessage("不存在该课程");
            return result;
        }
        CourseBuyLink courseBuyLink = new CourseBuyLink();
        BeanUtils.copyProperties(course,courseBuyLink);

        QueryWrapper<GoodLink> goodLinkQueryWrapper = new QueryWrapper<>();
        goodLinkQueryWrapper.eq("good_id",courseId);
        GoodLink goodLink = linkService.getOne(goodLinkQueryWrapper);
        if (goodLink == null) {
            result.setSuccess(false);
            return result;
        }
        courseBuyLink.setCover(goodLink.getCover());

        result.setResult(courseBuyLink);
        return result;
    }

    @Override
    public String getCourseChapterName(String courseChapterId) {
        CourseChapter chapter = chapterService.getById(courseChapterId);
        if (chapter == null) {
            return null;
        }
        return chapter.getTitle();
    }
}